<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="query.functionExplain"
        clearable
        size="small"
        placeholder="请输入脱敏函数说明"
        style="width:200px"
        class="filter-item"
      />
      <el-input
        v-model="query.functionName"
        clearable
        size="small"
        placeholder="请输入脱敏函数名称"
        style="width:200px"
        class="filter-item"
      />
      <rrOperation :crud="crud"/>
      <div style="margin-left: 10px;display: inline-block">
        <el-button class="filter-item" icon="el-icon-plus" size="mini" type="primary" @click="crud.toAdd">新增</el-button>
        <el-button v-if="crud.optShow.del" slot="reference" v-permission="permission.del" class="filter-item"
                   type="danger" icon="el-icon-delete" size="mini" :loading="crud.delAllLoading"
                   :disabled="crud.selections.length === 0"
                   @click="toDelete(crud.selections)">删除
        </el-button>
      </div>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      border
      max-height="300px"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="40"/>
      <el-table-column label="脱敏函数说明" prop="functionExplain" width="150px"/>
      <el-table-column label="脱敏函数名称" prop="functionName" width="180px"/>
      <el-table-column label="脱敏函数样例" prop="functionDetails"/>
      <el-table-column label="更新人" prop="createBy" width="80px"/>
      <el-table-column label="更新时间" prop="createTime" width="135px"/>
      <el-table-column fixed="right" label="验证" width="80px">
        <template slot-scope="scope">
          <el-button type="text" @click="toShowSimple(scope.row)">验证</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style=" float: right;">
      <!--分页组件-->
      <pagination/>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.add > 0"
      title="新增脱敏函数"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="120px">
        <el-form-item label="脱敏函数说明" prop="functionExplain">
          <el-input clearable size="small" style="width: 300px" placeholder="请输入脱敏函数说明" v-model="form.functionExplain"/>
        </el-form-item>
        <el-form-item label="脱敏函数名称" prop="functionName">
          <el-input clearable size="small" style="width: 300px" placeholder="请输入脱敏函数名称" v-model="form.functionName"/>
        </el-form-item>
        <el-form-item label="脱敏函数样例" prop="functionDetails">
          <el-input clearable size="small" style="width: 300px" type="textarea" :rows="3" placeholder="请输入脱敏函数描述"
                    v-model="form.functionDetails"/>
        </el-form-item>
        <div class="dialog-footer" style="width:100%;text-align: center">
          <el-button @click="crud.cancelCU">关 闭</el-button>
          <el-button type="primary" @click="crud.submitCU">保 存</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :before-close="cancelCU"
      :visible.sync="simpleFlag"
      title="验证脱敏函数"
      width="800px"
      append-to-body
    >
      <el-form ref="simpleForm" :model="simpleForm" :rules="simpleRules" :inline="true" label-width="100px">
        <el-row>
          <el-form-item prop="databaseName" label="库名称">
            <el-select v-model="simpleForm.databaseName" @change="databaseNameChange" style="width:260px">
              <el-option v-for="database in databaseList" :key="database" :value="database"/>
            </el-select>
          </el-form-item>
          <el-form-item prop="tableName" label="表名称">
            <el-select filterable v-model="simpleForm.tableName" @change="tableNameChange" style="width:260px">
              <el-option v-for="tblName in tableList" :key="tblName" :label="tblName" :value="tblName"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="fieldName" label="字段名称">
            <el-select filterable v-model="simpleForm.fieldName" @change="fieldNameChange" style="width:260px">
              <el-option v-for="item in metadataList" :key="item.name" :label="item.name" :value="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="脱敏函数" prop="functionDetails">
            <el-input clearable size="small" style="width: 260px" type="textarea" :rows="2" placeholder="请输入脱敏函数"
                      v-model="simpleForm.functionDetails"/>
          </el-form-item>
        </el-row>

        <div class="dialog-footer" style="width:100%;text-align: center">
          <el-button @click="cancelCU">关 闭</el-button>
          <el-button type="primary" @click="submitCU">查 询</el-button>
        </div>
        <el-table
          ref="table"
          :data="simpleData"
          v-loading="simpleDataLoading"
          border
          max-height="300px"
          style="margin-top: 15px"
        >
          <el-table-column label="原数据" prop="oldData"/>
          <el-table-column label="脱敏后数据" prop="newData"/>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import desensitizeFunctionApi from "@/api/dashboard/desensitizeFunction"
import hiveMetadataApi from "@/api/dataTransfer/common/hiveMetadata"
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import crudOperation from "@crud/CRUD.operation.vue"
import {validateChinese, validateCode} from '@/utils/validate'
import sourceRuleTableViewApi from '@/api/dataTransfer/common/sourceRuleTableView'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '数据脱敏函数配置',
  url: 'api/desensitizefunctionconf/page',
  crudMethod: {...desensitizeFunctionApi}
})
const defaultForm = {
  id: null,
  functionExplain: null,
  functionName: null,
  functionDetails: null
}
export default {
  name: 'DataDesensitizationRules',
  components: {crudOperation, rrOperation, pagination},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    var validateFunctionExplain = (rule, value, callback) => {
      if (value != null && value !== '') {
        let params = {functionExplain: value, page: 10000000}
        desensitizeFunctionApi.findListByPage(params).then(res => {
          if (res.totalElements > 0) {
            res.content.forEach(item => {
              let isExist = false
              if (value === item.functionExplain) {
                isExist = true
              }
              if (isExist) {
                callback(new Error('该函数说明已存在!'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }

        })
      } else {
        callback()
      }
    }
    var validateFunctionName = (rule, value, callback) => {
      if (value != null && value !== '') {
        let params = {functionName: value, page: 10000000}
        desensitizeFunctionApi.findListByPage(params).then(res => {
          if (res.totalElements > 0) {
            res.content.forEach(item => {
              let isExist = false
              if (value === item.functionName) {
                isExist = true
              }
              if (isExist) {
                callback(new Error('该函数名称已存在!'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }

        })
      } else {
        callback()
      }
    }
    return {
      simpleFlag: false,
      simpleDataLoading: false,
      simpleForm: {
        databaseName: null,
        tableName: null,
        fieldName: null,
        functionDetails: null
      },
      showFunctionsObject: null,
      simpleRules: {
        databaseName: [
          {required: true, message: '请选择库名', trigger: 'change'}
        ],
        tableName: [
          {required: true, message: '请选择表名', trigger: 'change'}
        ],
        fieldName: [
          {required: true, message: '请选择字段', trigger: 'change'}
        ],
        functionDetails: [
          {required: true, message: '请输入脱敏函数示例', trigger: 'blur'}
        ],
      },
      simpleData: [],
      permission: {
        add: ['admin', 'scriptPack:add'],
        del: ['admin', 'scriptPack:del']
      },
      rules: {
        functionExplain: [
          {required: true, message: '请输入脱敏函数说明', trigger: 'blur'},
          {validator: validateChinese, trigger: 'blur'},
          {validator: validateFunctionExplain, trigger: 'blur'}
        ],
        functionName: [
          {required: true, message: '请输入脱敏函数名称', trigger: 'blur'},
          {validator: validateCode, trigger: 'blur'},
          {validator: validateFunctionName, trigger: 'blur'}
        ],
        functionDetails: [
          {required: true, message: '请输入脱敏函数描述', trigger: 'blur'}
        ]
      },
      tableList: [],
      databaseList: [],
      metadataList: []
    }
  },
  created() {
    this.databasesList()
  },
  methods: {
    databasesList() {
      this.databaseList = []
      sourceRuleTableViewApi.databases().then(res => {
        this.databaseList = res
      })
    },
    databaseNameChange(databaseName) {
      this.tableList = []
      this.metadataList = []
      this.simpleForm.tableName = null
      this.simpleForm.fieldName = null
      let functionsObject = JSON.parse(JSON.stringify(this.showFunctionsObject))
      this.simpleForm.functionDetails = functionsObject.functionDetails
      sourceRuleTableViewApi.tables(databaseName).then(res => {
        this.tableList = res
      })
    },
    tableNameChange(tableName) {
      this.metadataList = []
      this.simpleForm.fieldName = null
      let functionsObject = JSON.parse(JSON.stringify(this.showFunctionsObject))
      this.simpleForm.functionDetails = functionsObject.functionDetails
      hiveMetadataApi.metadata(this.simpleForm.databaseName, tableName).then(res => {
        this.metadataList = res
      })
    },
    fieldNameChange(fieldName) {
      let functionsObject = JSON.parse(JSON.stringify(this.showFunctionsObject))
      this.simpleForm.functionDetails = functionsObject.functionDetails.replace("field_name", fieldName);
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    submitCU() {
      this.$refs['simpleForm'].validate(valid => {
        if (!valid) {
          return
        }
        this.simpleDataLoading = true
        this.simpleData = []
        hiveMetadataApi.funcationTest(this.simpleForm).then(res => {
          this.simpleDataLoading = false
          this.simpleData = res
        }).catch(err => {
          this.simpleDataLoading = false
        })
      })
    },
    toShowSimple(row) {
      this.simpleFlag = true
      this.showFunctionsObject = JSON.parse(JSON.stringify(row))
      this.simpleForm.functionDetails = row.functionDetails
    },
    cancelCU() {
      this.simpleFlag = false
    }
  }
}
</script>
<style scoped>

</style>
